//
//  FNBanner.swift
//  FNBanner
//
//  Created by Fnoz on 2016/10/24.
//  Copyright © 2016年 Fnoz. All rights reserved.
//

import UIKit
import SnapKit

typealias BannerSelectBlock = ((_ index: Int?) -> ())

let loopTimes = 1024
let originLoopTimes = 64

enum BannerStyle {
    case style0
    case style1
    case style2
}

class FNBanner: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    //轮播图样式
    var bannerStyle = BannerStyle.style0 {
        didSet {
            switch bannerStyle {
            case .style0:
                collectionView.isPagingEnabled = true
                collectionView.collectionViewLayout = UICollectionViewFlowLayout()
            case .style1:
                collectionView.isPagingEnabled = false
                collectionView.collectionViewLayout = FNBannerCollectionViewFlowLayout1(itemSize: CGSize.zero)
            case .style2:
                collectionView.isPagingEnabled = false
                collectionView.collectionViewLayout = FNBannerCollectionViewFlowLayout2(itemSize: CGSize.zero)
                break
            }
            collectionView.reloadData()
        }
    }
    
    //图片url们
    var imageUrlArray = NSArray() {
        didSet {
            if collectionView.isKind(of: UICollectionView.self) {
                collectionView.reloadData()
                if (1 == imageUrlArray.count && .style0 == bannerStyle) {
                    self.collectionView.scrollToItem(at: IndexPath.init(row: 0, section: 0), at: .centeredHorizontally, animated: false)
                }
                else {
                    self.collectionView.scrollToItem(at: IndexPath.init(row: self.imageUrlArray.count * originLoopTimes, section: 0), at: .centeredHorizontally, animated: false)
                }
                pageControl.numberOfPages = imageUrlArray.count
            }
        }
    }
    
    //是否无限轮播
    var loopAble = true
    
    //非0则自动轮播
    var autoScrollTimeInterval = 0.0 {
        didSet {
            updateTimer()
        }
    }
    
    //图片占位图
    var placeHolder: UIImage?
    
    //Banner点击回调block
    var selectBlock: BannerSelectBlock?
    
    //当前index
    var currentIndex: Int {
        set {
            if (1 == imageUrlArray.count && .style0 == bannerStyle) {
                self.collectionView.scrollToItem(at: IndexPath.init(row: 0, section: 0), at: .centeredHorizontally, animated: false)
            }
            else if (self.imageUrlArray.count * originLoopTimes + newValue < imageUrlArray.count * loopTimes) {
                self.collectionView.scrollToItem(at: IndexPath.init(row: imageUrlArray.count * originLoopTimes + newValue, section: 0), at: .centeredHorizontally, animated: false)
            }
        }
        get {
            return privateCurrentIndex % imageUrlArray.count
        }
    }
    
    //是否隐藏pageControl
    var hiddenPageControl = false {
        didSet {
            pageControl.isHidden = hiddenPageControl
        }
    }
    
    //pageControl颜色
    var pageControlCurrentTintColor = UIColor.white {
        didSet {
            pageControl.currentPageIndicatorTintColor = pageControlCurrentTintColor
        }
    }
    
    var pageControlTintColor = UIColor.init(white: 1, alpha: 0.5) {
        didSet {
            pageControl.pageIndicatorTintColor = pageControlTintColor
        }
    }
    
    private var layout = UICollectionViewFlowLayout()
    private var collectionView: UICollectionView!
    private let pageControl = UIPageControl()
    private var timer: Timer?
    private var privateCurrentIndex = 0
    
    override func awakeFromNib() {
        initView()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initView()
    }
    
    func initView() {
        layout.scrollDirection = .horizontal
        collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.decelerationRate = 0.1
        collectionView.register(FNBannerCollectionViewCell0.self, forCellWithReuseIdentifier:NSStringFromClass(FNBannerCollectionViewCell0.self))
        collectionView.register(FNBannerCollectionViewCell1.self, forCellWithReuseIdentifier:NSStringFromClass(FNBannerCollectionViewCell1.self))
        collectionView.register(FNBannerCollectionViewCell2.self, forCellWithReuseIdentifier:NSStringFromClass(FNBannerCollectionViewCell2.self))
        addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.width.equalTo(self)
            make.height.equalTo(self)
            make.center.equalTo(self)
        }
        
        addSubview(pageControl)
        pageControl.currentPageIndicatorTintColor = pageControlCurrentTintColor
        pageControl.pageIndicatorTintColor = pageControlTintColor
        pageControl.hidesForSinglePage = true
        pageControl.snp.makeConstraints { (make) in
            make.left.equalTo(10)
            make.bottom.equalTo(self.snp.bottom).offset(-10)
            make.width.equalTo(60)
            make.height.equalTo(5)
//            make.centerX.equalTo(self)
//            make.centerY.equalTo(self.snp.bottom).offset(-12)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func updateTimer() {
        timer?.invalidate()
        if (1 == imageUrlArray.count && .style0 == bannerStyle) {
            return;
        }
        if (autoScrollTimeInterval > 0) {
            if #available(iOS 10.0, *) {
                timer = Timer.scheduledTimer(withTimeInterval: TimeInterval(autoScrollTimeInterval),
                                             repeats: true,
                                             block: { (timer) in
                                                self.everyScrollTimeDo()
                })
            } else {
                timer = Timer.scheduledTimer(timeInterval: TimeInterval(autoScrollTimeInterval),
                                             target: self,
                                             selector: #selector(everyScrollTimeDo),
                                             userInfo: nil,
                                             repeats: true)
            }
        }
    }
    
    func everyScrollTimeDo() {
        self.handleLoopThing()
        if (self.privateCurrentIndex + 1 < self.imageUrlArray.count * loopTimes) {
            self.collectionView.scrollToItem(at: IndexPath.init(row: self.privateCurrentIndex + 1, section: 0), at: .centeredHorizontally, animated: true)
        }
    }
    
    func handleLoopThing() {
        if !loopAble || (1 == imageUrlArray.count && .style0 == bannerStyle) {
            return
        }
        if (self.privateCurrentIndex + 1 >= self.imageUrlArray.count * loopTimes) {
            self.collectionView.scrollToItem(at: IndexPath.init(row: self.imageUrlArray.count * (originLoopTimes - 1) + self.currentIndex, section: 0), at: .centeredHorizontally, animated: false)
            self.privateCurrentIndex = self.imageUrlArray.count * (originLoopTimes - 1) + self.currentIndex
        }
        if (self.privateCurrentIndex - 1 < 0) {
            self.collectionView.scrollToItem(at: IndexPath.init(row: self.imageUrlArray.count * originLoopTimes + self.currentIndex, section: 0), at: .centeredHorizontally, animated: false)
            self.privateCurrentIndex = self.imageUrlArray.count * originLoopTimes + self.currentIndex
        }
    }
    
    // MARK: UICollectionView Delegate
    private func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if (1 == imageUrlArray.count && .style0 == bannerStyle) {
            return 1
        }
        return imageUrlArray.count * loopTimes
    }
        
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = FNBannerCollectionViewCellFactory.cell(collectionView: collectionView, indexPath: indexPath, style: bannerStyle, imageUrl: imageUrlArray[indexPath.row % imageUrlArray.count] as? String, placeHolder: placeHolder)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return FNBannerCollectionViewCellFactory.cellSize(style: bannerStyle, bannerSize: bounds.size)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0;
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectBlock?(indexPath.row % imageUrlArray.count)
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        handleLoopThing()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        updateTimer()
        
        let cellWidth = FNBannerCollectionViewCellFactory.cellSize(style: bannerStyle, bannerSize: bounds.size).width
        privateCurrentIndex = Int((scrollView.contentOffset.x + cellWidth * 0.5) / cellWidth);
        pageControl.currentPage = currentIndex
        
        handleLoopThing()
    }
}
